package com.lingtianyu.tech.erbaoshen.core.consumer.bean;

import com.lingtianyu.tech.erbaoshen.core.consumer.bean.annotation.Reference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;

@Slf4j
public class ReferenceBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object obj, String beanName) throws BeansException {
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {
            Reference reference = declaredField.getAnnotation(Reference.class);
            if (reference != null) {
                Object bean = getFieldByField(declaredField, reference);
                declaredField.setAccessible(true);
                try {
                    declaredField.set(obj, bean);
                } catch (IllegalAccessException e) {
                    log.error("@DaoAutowired error, ", e);
                }
            }
        }
        return obj;
    }

    //根据属性，获取对应的接口信息
    private Object getFieldByField(Field field, Reference reference) {
        Class<?> type = field.getType();
        return Proxy.newProxyInstance(type.getClassLoader(), new Class[]{type}, new ReferenceBeanProxy(reference, type));
    }
}
